<template>
  <div class="page-mobile-course_play">
    <!-- <van-nav-bar class="cd-header" :title="course_obj.courseName">
      <template #left>
        <van-icon name="arrow-left" @click="onClickLeft" />
      </template>
    </van-nav-bar> -->
    <white-header
      :isShowTopNav="true"
      :isShowBack="true"
      :isShowRight="true"
      :title="course_obj.courseName"
    ></white-header>
    <div class="fixed-box"></div>
    <div class="video-box" v-if="chapter_obj.isLive != 3">
      <template
        v-if="
          is_had_course &&
            !is_hidden_content &&
            chapter_obj.isLive != 0 &&
            [2, 3].includes(live_status)
        "
      >
        <div class="live-info">
          <p v-if="live_status == 2 && getChapterCount != -1">
            距离直播开始还有
            <van-count-down :time="getChapterCount">
              <template v-slot="timeData">
                <span class="block">{{ timeData.days }}</span>
                <span class="colon">{{
                  $t("locale.mobile.courseDetail.t5")
                }}</span>
                <span class="block">{{ timeData.hours }}</span>
                <span class="colon">{{
                  $t("locale.mobile.courseDetail.t6")
                }}</span>
                <span class="block">{{ timeData.minutes }}</span>
                <span class="colon">{{
                  $t("locale.mobile.courseDetail.t7")
                }}</span>
              </template>
            </van-count-down>
          </p>
          <p v-if="live_status == 3">
            当前直播已经结束
          </p>
        </div>
      </template>
      <template v-if="!is_hidden_content">
        <no-ssr>
          <videos-player
            :sources="sources"
            :timeUpdate="websocketsend"
            :updateLastStudyTime="updateLastStudyTime"
            :startTime="video_obj.time"
            :chapter_obj="chapter_obj"
            :isJump="kl_md.KLST == 1 && !is_had_course && chapter_obj.isJump == 1"
            @setSources="setSources"
            ref="video"
            v-if="
              (is_had_course && [0].includes(chapter_obj.isLive)) ||
                (kl_md.KLST == 1 &&
                  !is_had_course &&
                  chapter_obj.isJump == 1 &&
                  token &&
                  Object.keys(user_info).length > 0) ||
                (is_had_course &&
                  [1].includes(chapter_obj.isLive) &&
                  [1].includes(live_status))
            "
          ></videos-player>
        </no-ssr>
        <no-ssr>
          <rtc-live
            :chapter_obj="chapter_obj"
            :teacher_obj="teacher_obj"
            v-if="
              is_had_course &&
                [2].includes(chapter_obj.isLive) &&
                [1].includes(live_status)
            "
          ></rtc-live>
        </no-ssr>
      </template>
      <!-- <img
        style="width:auto;height:100%"
        :src="course_obj.iconPath"
        v-if="is_hidden_content"
      /> -->
      <!-- <img
        style="width:auto;height:100%"
        src="/img/test.png"
        v-if="is_hidden_content"
      /> -->
      <div
        class="bottom-bar"
        v-show="
          !is_had_course &&
            !is_hidden_content &&
            !is_show_price &&
            (!chapter_obj.isJump || Object.keys(user_info).length == 0)
        "
      >
        <div class="buyless" v-if="!is_hidden_content && !is_show_price">
          <span v-if="token && Object.keys(user_info).length > 0">{{
            is_related_member
              ? "开通" + member_related + "免费或者单独购买即可享受课程服务哦"
              : $t("locale.mobile.courseDetail.t1")
          }}</span>
          <span v-else>您尚未登录,请先登录再观看哟！</span>
        </div>
        <div class="course-price" v-show="!is_show_price">
          <!-- 开启了折扣 -->
          <template v-if="course_obj.isDiscount">
            <div class="macket-price">
              <van-icon name="gold-coin-o" />
              <span class="price-font">{{
                course_obj.isFree ? 0 : course_obj.discountPrice
              }}</span
              >{{ $t("locale.mobile.courseDetail.price") }}
            </div>
            <div class="origin-price">
              <span class="price-font"
                >{{ $t("locale.mobile.courseDetail.t2") }}：{{ course_obj.price
                }}{{ $t("locale.mobile.courseDetail.price") }}</span
              >
            </div>
          </template>
          <!-- 没有开启折扣 -->
          <template v-if="!course_obj.isDiscount">
            <!-- <div class="macket-price">
              <van-icon name="gold-coin-o" />
              <span class="price-font">{{
                course_obj.isFree ? 0 : course_obj.price
              }}</span
              >{{ $t("locale.mobile.courseDetail.price") }}
            </div> -->
            <div class="macket-price">
              <van-icon name="gold-coin-o" />
              <span class="price-font">{{
                Number(
                  course_obj.isFree
                    ? 0
                    : isMemberFree
                    ? 0
                    : !is_member
                    ? course_obj.price
                    : user_member.memberLevel === 0
                    ? course_obj.smallMemberPrice
                    : user_member.memberLevel === 1
                    ? course_obj.middleMemberPrice
                    : user_member.memberLevel === 2
                    ? course_obj.highMemberPrice
                    : 0
                ).toFixed(2)
              }}</span
              >{{ $t("locale.mobile.courseDetail.price") }}
            </div>
          </template>
          <div class="activity" v-show="course_obj.isDiscount">
            <div v-show="getCount === -1">
              {{ $t("locale.mobile.courseDetail.t3") }}
            </div>
            <div v-show="getCount > 0">
              {{ $t("locale.mobile.courseDetail.t4") }}
              <van-count-down :time="getCount">
                <template v-slot="timeData">
                  <span class="block">{{ timeData.days }}</span>
                  <span class="colon">{{
                    $t("locale.mobile.courseDetail.t5")
                  }}</span>
                  <span class="block">{{ timeData.hours }}</span>
                  <span class="colon">{{
                    $t("locale.mobile.courseDetail.t6")
                  }}</span>
                  <span class="block">{{ timeData.minutes }}</span>
                  <span class="colon">{{
                    $t("locale.mobile.courseDetail.t7")
                  }}</span>
                </template>
              </van-count-down>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div
      class="tuwen_box"
      id="tuwen_box"
      v-if="chapter_obj.isLive == 3"
      v-html="chapter_obj.chapterDescription"
    ></div>
    <div class="fixed-box" style="height:4rem;overflow:hidden;"></div>
    <van-tabs v-model="active">
      <van-tab name="detail" title="学习内容" v-if="chapter_obj.isLive != 3">
        <div
          style="padding-top:.2rem"
          v-html="chapter_obj.chapterDescription"
          v-if="chapter_obj.chapterDescription"
        ></div>
        <div
          style="padding:.2rem .288rem 0;"
          v-if="!chapter_obj.chapterDescription"
        >
          暂无学习内容
        </div>
        <div
          class="task_list"
          v-if="
            token &&
              Object.keys(user_info).length > 0 &&
              is_had_course &&
              kl_md.KLZYGL == 1
          "
        >
          <div class="task_list_title">课后作业</div>
          <div
            class="task_list_item"
            v-for="(item, index) in videoTaskList"
            :key="index"
          >
            <p class="video_name">
              作业{{ index + 1 }} 《{{ item.videoName }}》
            </p>
            <p class="task_name">{{ item.taskName }}</p>
            <div class="task_btn_list">
              <div
                class="task_item_btn"
                v-if="item.resourceUrl"
                @click="downloadResource(item.resourceUrl, item.taskName)"
              >
                下载资源
              </div>
              <div class="task_item_btn" v-else>暂无资源</div>
              <Upload
                class="avatar-uploader"
                ref="avatar-uploader"
                action=""
                :before-upload="afterRead"
                :show-file-list="false"
                :auto-upload="false"
                :show-upload-list="false"
                @click="false"
                v-if="item.taskType == 2"
              >
                <div
                  @click="setTask(item, !!item.userTask, $event)"
                  :class="['task_item_btn', item.userTask ? 'bg_pink' : '']"
                >
                  {{ item.userTask ? "已经上传" : "上传作业" }}
                </div>
              </Upload>
              <div
                @click="setTask(item, !!item.userTask, $event)"
                v-else
                :class="['task_item_btn', item.userTask ? 'bg_pink' : '']"
              >
                {{ item.userTask ? "考试完成" : "开始考试" }}
              </div>
              <!-- <div class="task_item_btn">下载作业</div> -->
            </div>
          </div>
        </div>
      </van-tab>
      <van-tab name="chapter" title="课程目录">
        <div class="chapter">
          <div class="chapter-box">
            <div
              class="chapter-list"
              v-for="(itemOne, indexOne) in chapter_tree"
              :key="indexOne"
            >
              <template v-if="itemOne.children.length > 0">
                <div class="chapter-title-one">
                  {{ itemOne.chapterName }}
                </div>
                <div
                  v-for="(itemTwo, indexTwo) in itemOne.children"
                  :key="indexTwo"
                >
                  <template v-if="itemTwo.children.length > 0">
                    <!-- <div class="chapter-title-one">
                      {{ itemOne.chapterName }}
                    </div> -->
                    <div class="chapter-list">
                      <div class="chapter-title-two">
                        {{ itemTwo.chapterName }}
                      </div>
                      <div
                        :class="[
                          'chapter-one',
                          chapterId == itemThree.id ? 'active' : ''
                        ]"
                        v-for="(itemThree, indexThree) in itemTwo.children"
                        :key="indexThree"
                        @click="pushRouter(itemThree)"
                      >
                        <div class="chapter-left">
                          {{ itemThree.chapterName }}
                        </div>
                        <div class="chapter-right" v-if="itemThree.isJump == 1">
                          免费试学
                        </div>
                        <van-tag
                          type="danger"
                          class="tag-study"
                          v-if="!itemThree.isDone"
                          >未完成</van-tag
                        >
                        <van-tag
                          type="success"
                          class="tag-study"
                          v-if="itemThree.isDone"
                          >已完成</van-tag
                        >
                      </div>
                    </div>
                  </template>
                  <template v-else>
                    <!-- <div class="chapter-title-one">
                      {{ itemOne.chapterName }}
                    </div> -->
                    <div class="chapter-list">
                      <div
                        :class="[
                          'chapter-one',
                          chapterId == itemTwo.id ? 'active' : ''
                        ]"
                        @click="pushRouter(itemTwo)"
                      >
                        <div class="chapter-left">
                          {{ itemTwo.chapterName }}
                        </div>
                        <div class="chapter-right" v-if="itemTwo.isJump == 1">
                          免费试学
                        </div>
                        <van-tag
                          type="danger"
                          class="tag-study"
                          v-if="!itemTwo.isDone"
                          >未完成</van-tag
                        >
                        <van-tag
                          type="success"
                          class="tag-study"
                          v-if="itemTwo.isDone"
                          >已完成</van-tag
                        >
                      </div>
                    </div>
                  </template>
                </div>
              </template>
              <template v-else>
                <div>
                  <div class="chapter-list">
                    <div
                      :class="[
                        'chapter-two',
                        chapterId == itemOne.id ? 'active' : ''
                      ]"
                      @click="pushRouter(itemOne)"
                    >
                      <div class="chapter-left">{{ itemOne.chapterName }}</div>
                      <div class="chapter-right" v-if="itemOne.isJump == 1">
                        免费试学
                      </div>
                      <van-tag
                        type="danger"
                        class="tag-study"
                        v-if="!itemOne.isDone"
                        >未完成</van-tag
                      >
                      <van-tag
                        type="success"
                        class="tag-study"
                        v-if="itemOne.isDone"
                        >已完成</van-tag
                      >
                    </div>
                  </div>
                </div>
              </template>
            </div>
          </div>
        </div>
      </van-tab>
      <van-tab
        name="courseware"
        title="学习课件"
        v-if="token && Object.keys(user_info).length > 0 && is_had_course"
      >
        <div class="courseware">
          <div class="ware" v-if="chapter_obj.courseWarePath">
            <div class="ware-left">{{ chapter_obj.chapterName }}课件</div>
            <div class="ware-right">
              <a
                :href="chapter_obj.courseWarePath"
                :download="chapter_obj.chapterName"
                >下载</a
              >
            </div>
          </div>

          <!-- <iframe
            v-if="!is_in_minigram"
            :src="
              `https://view.officeapps.live.com/op/embed.aspx?src=${encodeURIComponent(
                chapter_obj.courseWarePath
              )}`
            "
            v-show="isMircosoftRead"
            class="preview-iframe"
            frameborder="0"
          >
            This is an embedded
            <a target="_blank" href="http://office.com">Microsoft Office</a>
            document, powered by
            <a target="_blank" href="http://office.com/webapps"
              >Office Online</a
            >
          </iframe> -->
          <img
            class="preview-img"
            :src="chapter_obj.courseWarePath"
            v-show="
              /.(gif|jpg|jpeg|png|gif|jpg|png)$/.test(
                chapter_obj.courseWarePath
              )
            "
          />
          <!-- <van-collapse v-model="chapter_active">
            <component :is="component1" :datas="chapter_tree"></component>
          </van-collapse> -->
        </div>
      </van-tab>
      <van-tab
        name="groupchat"
        :title="$t('locale.mobile.courseDetail.t16')"
        v-if="is_had_course && chapter_obj.isLive && chapter_obj.isLive != 3"
      >
        <group-chat
          :chapter_obj="chapter_obj"
          :teacher_obj="teacher_obj"
          :live_status="live_status"
        ></group-chat>
      </van-tab>
    </van-tabs>
    <div
      class="bottom-area"
      v-show="
        !is_hidden_content &&
          (!is_show_price || course_obj.isFree == 1) &&
          !is_had_course
      "
    >
      <div class="btn-buy" v-if="!isPublishedBefore">
        <van-button type="primary" block @click="toBuy">{{
          course_obj.isFree
            ? $t("locale.mobile.courseDetail.t21")
            : $t("locale.mobile.courseDetail.t17")
        }}</van-button>
      </div>
      <div class="btn-buy" v-if="isPublishedBefore" @click="$router.push('/m/group-booking?type=1')">
        <van-button
          :style="{
            backgroundColor: THEME_COLOR_LIGHTER,
            borderColor: THEME_COLOR_LIGHTER
          }"
          type="primary"
          block
          >正在拼单中</van-button
        >
      </div>
    </div>
    <div
      :class="[
        'signin_box',
        maySignInCourse || hasSignInCourse ? 'may_sign' : ''
      ]"
      v-if="kl_md.KLKCQD == 1 && is_had_course"
      @click="courseSignInHandle()"
    >
      <p>签到倒计时</p>
      <div class="signin_text">
        <span v-if="maySignInCourse">签到</span>
        <span v-else-if="hasSignInCourse">已签</span>
        <span v-else>{{ countDownSecond }}</span>
      </div>
    </div>
  </div>
</template>

<script>
import { getCourse, saveCourseSignIn, downloadReport } from "~/api/course";
import { getChapter, getVideoLastTime, getLastStudyList } from "~/api/chapter";
import { getTeacher } from "~/api/account/user";
import { downloadFile } from "~/api/common";
import { saveOrder } from "~/api/order";
import { getMyTaskList, saveUserTask, getVideoUrl } from "~/api/task";
import { mapState, mapActions, mapMutations } from "vuex";
import { socketUrl } from "~/config/conf";
import ChapterTree from "~/components/mobile/ChapterTree";
import ChapterWareTree from "~/components/mobile/ChapterWareTree";
import VideosPlayer from "~/components/mobile/VideosPlayer";
import GroupChat from "~/components/mobile/GroupChat";
// import RtcLive from "~/components/mobile/RtcLive";
import RtcLive from "~/components/mobile/TRtcLive";
import { getMimeType } from "~/utils/commonfun";
import WhiteHeader from "~/components/mobile/WhiteHeader.vue";
import { blobToDataURL } from "~/utils/file";
import {
  getGroupBookingListByCourse,
  getGroupBookingGroupsByCourse,
  getGroupBookingGroupsByCourseAndUser
} from "~/api/group-booking";
import {
  getMemberInfo,
  getMember,
  getMemberList,
  getMemberConfig
} from "~/api/member";

export default {
  components: {
    ChapterTree,
    ChapterWareTree,
    VideosPlayer,
    GroupChat,
    RtcLive,
    WhiteHeader
  },
  // head() {
  //   return {
  //     meta: this.is_set_secure
  //       ? [
  //           {
  //             hid: "http-equiv",
  //             "http-equiv": "Content-Security-Policy",
  //             name: "Content-Security-Policy",
  //             content: "upgrade-insecure-requests"
  //           }
  //         ]
  //       : []
  //   };
  // },
  data() {
    return {
      countDownSecond: "5:00",
      countDownTimer: null,
      maySignInCourse: false,
      signInCourseFlag: false,
      active: "chapter",
      course_obj: {
        name: "",
        isFree: 0
      },
      teacher_obj: {}, //课程老师信息
      chapter_list: [], //章节列表
      chapter_tree: [], //章节树
      chapter_active: [], //折叠面板打开
      chapter_obj: {
        courseId: 0,
        chapterName: "",
        chapterIndex: 1,
        chapterLevel: 1,
        chapterDescription: "",
        fatherLevelId: 0,
        live: "hahah",
        courseWarePath: null,
        fileName: "",
        filePath: "",
        fileType: null,
        fileSize: null,
        createTime: 1591012869000,
        createUserId: null,
        createUserName: null,
        updateTime: 1591012869000,
        updateUserId: null,
        updateUserName: null,
        liveEndTime: 1591012869000,
        liveStartTime: 1591012869000,
        isLive: 0
      },
      //正在播放的章节
      video_obj: {
        time: 0
      }, //视频其他数据
      websock: null,
      component: "ChapterTree",
      component1: "ChapterWareTree",
      sources: "",
      is_had_course: false,
      last_require_lime: new Date().getTime(), //上次上报视频时间的时间戳
      member_config: {
        isOpenMember: 0
      },
      memberList: [],
      timer: null, //节流计时器
      socketFailedCount: 0, //socket重连计数器
      minChapterVedioList: [], //可播放的视频章节ids
      myTaskList: [], //我的作业
      gbConfig: {
        creatTime: 1613703969931,
        endTime: 1629255969931,
        goodsId: 12,
        id: 5,
        imitate: 1,
        lastMoney: 1800,
        personNum: 2,
        startTime: 1613703969931,
        troopsTime: 1440,
        is_set: false // 是否是拼团商品
      }, //拼团信息
      isPublishedBefore: false
    };
  },
  computed: {
    ...mapState({
      user_info(state) {
        return state.user_info;
      },
      major_list(state) {
        return state.major_list;
      },
      buy_record_list(state) {
        return state.buy_record_list;
      },
      is_mobile(state) {
        return state.is_mobile;
      },
      token(state) {
        return state.token;
      },
      is_ios(state) {
        return state.is_ios;
      },
      is_in_wechat(state) {
        return state.is_in_wechat;
      },
      is_in_minigram(state) {
        return state.is_in_minigram;
      },
      is_hidden_content(state) {
        return state.is_hidden_content;
      },
      is_member(state) {
        return JSON.stringify(state.member_info) != "{}";
      },
      user_member(state) {
        return state.member_info;
      },
      member_discount(state) {
        return state.member_discount;
      },
      kl_md(state) {
        return state.kl_md;
      },
      is_wechat_ios_limit(state) {
        return state.is_wechat_ios_limit;
      },
      sign_in_course_list(state) {
        return state.sign_in_course_list;
      },
      THEME_COLOR_LIGHTER(state) {
        return state.THEME_COLOR_LIGHTER;
      }
    }),
    //1.允许拼团  2.拼团还没开始  3.拼团结束
    group_booking_status() {
      const { endTime, startTime } = this.gbConfig;
      let currentTime = new Date().getTime();
      if (startTime <= currentTime && currentTime < endTime) {
        return 1;
      } else if (startTime > currentTime) {
        return 2;
      } else if (endTime < currentTime) {
        return 3;
      }
    },
    chapterVedioList() {
      if (this.is_had_course) {
        return this.minChapterVedioList;
      } else {
        return this.minChapterVedioList.filter(item => item.isJump == 1);
      }
    },
    videoTaskList() {
      return this.myTaskList.filter(item => item.videoId == this.chapterId);
    },
    isMemberFree() {
      if (
        this.member_discount &&
        JSON.stringify(this.member_discount) !== "{}"
      ) {
        if (
          this.member_discount.majorIds.includes(this.course_obj.majorId) ||
          this.member_discount.courseIds.includes(this.course_obj.id)
        ) {
          return true;
        } else {
          return false;
        }
      }
    },
    is_show_price() {
      if (this.is_wechat_ios_limit) {
        return this.is_ios && this.is_in_wechat;
      } else {
        return false;
      }
    },
    courseId() {
      return this.$route.query.id;
    },
    hasSignInCourse() {
      return this.sign_in_course_list.findIndex(
        item => item.courseId == this.courseId
      ) != -1
        ? true
        : false;
    },
    chapterId() {
      return this.$route.query.chapterId;
    },
    isMircosoftRead() {
      const { courseWarePath } = this.chapter_obj;
      let xls = /^.*\.(?:xls)$/;
      let xlsx = /^.*\.(?:xlsx)$/;
      let docx = /^.*\.(?:docx)$/;
      let doc = /^.*\.(?:doc)$/;
      let ppt = /^.*\.(?:ppt)$/;
      let pptx = /^.*\.(?:pptx)$/;
      if (
        xls.test(courseWarePath) ||
        xlsx.test(courseWarePath) ||
        doc.test(courseWarePath) ||
        docx.test(courseWarePath) ||
        pptx.test(courseWarePath) ||
        ppt.test(courseWarePath)
      ) {
        return true;
      } else {
        return false;
      }
    },
    getCount() {
      let time_far = this.course_obj.discountEndTime - new Date().getTime();
      if (time_far > 0) {
        return time_far;
      } else {
        return -1;
      }
    },
    getChapterCount() {
      let time_far = this.chapter_obj.liveStartTime - new Date().getTime();
      if (time_far > 0) {
        return time_far;
      } else {
        return -1;
      }
    },
    is_set_secure() {
      if (process.client) {
        let is_https_resource = /^https/.test(this.chapter_obj.live);
        let is_https_domain = window.location.protocol == "https:";
        //https包含http资源返回true
        if (is_https_domain && !is_https_resource) {
          return true;
        } else {
          return false;
        }
      } else {
        return false;
      }
    },
    //1.正在直播区间  2.直播还没开始  3.直播结束
    live_status() {
      const { liveEndTime, liveStartTime } = this.chapter_obj;
      let currentTime = new Date().getTime();
      if (liveStartTime <= currentTime && currentTime < liveEndTime) {
        return 1;
      } else if (liveStartTime > currentTime) {
        return 2;
      } else if (liveEndTime < currentTime) {
        return 3;
      }
    },
    isShowSmallMemberAdvert() {
      if (this.member_config.isOpenMember === 1 && this.memberList.length > 0) {
        if (
          JSON.parse(this.memberList[0].majorIds).includes(
            this.course_obj.majorId
          )
        ) {
          // console.log("该课程在初级免费专业中");
          return true;
        } else if (
          JSON.parse(this.memberList[0].courseIds).includes(this.course_obj.id)
        ) {
          // console.log("该课程在初级免费课程中");
          return true;
        } else {
          return false;
        }
      } else {
        return false;
      }
    },
    isShowMiddleMemberAdvert() {
      if (this.member_config.isOpenMember === 1 && this.memberList.length > 0) {
        if (
          JSON.parse(this.memberList[1].majorIds).includes(
            this.course_obj.majorId
          )
        ) {
          // console.log("该课程在中级免费专业中");
          return true;
        } else if (
          JSON.parse(this.memberList[1].courseIds).includes(this.course_obj.id)
        ) {
          // console.log("该课程在中级免费课程中");
          return true;
        } else {
          return false;
        }
      } else {
        return false;
      }
    },
    isShowHighMemberAdvert() {
      if (this.member_config.isOpenMember === 1 && this.memberList.length > 0) {
        if (
          JSON.parse(this.memberList[2].majorIds).includes(
            this.course_obj.majorId
          )
        ) {
          // console.log("该课程在高级免费专业中");
          return true;
        } else if (
          JSON.parse(this.memberList[2].courseIds).includes(this.course_obj.id)
        ) {
          // console.log("该课程在高级免费课程中");
          return true;
        } else {
          return false;
        }
      } else {
        return false;
      }
    },
    is_related_member() {
      if (this.kl_md.KLHY == 1) {
        if (this.member_config.isOpenMember === 1) {
          if (
            !this.isShowSmallMemberAdvert &&
            !this.isShowMiddleMemberAdvert &&
            !this.isShowHighMemberAdvert
          ) {
            return false;
          } else {
            if (Object.keys(this.user_member).length > 0) {
              return false;
            } else {
              return true;
            }
          }
        } else {
          return false;
        }
      } else {
        return false;
      }
    },
    member_related() {
      let text = "";
      if (this.isShowSmallMemberAdvert) {
        text = this.member_config.smallMemberName;
      }
      if (this.isShowMiddleMemberAdvert) {
        text += "、" + this.member_config.middleMemberName;
      }
      if (this.isShowHighMemberAdvert) {
        text += "、" + this.member_config.highMemberName;
      }
      return text;
    }
  },
  watch: {
    $route(new_val, old_val) {
      if (new_val.name == "MCoursePlay" && old_val.name == "MCoursePlay") {
        let chapter_obj = this.chapter_list.filter(
          i => i.id == new_val.query.chapterId
        )[0];
        // console.log("chapter_obj==============00", chapter_obj);
        this.$set(this, "chapter_obj", chapter_obj);
        // if (this.chapter_obj.isLive == 3) {
        //   this.active = 'chapter';
        // }
        if (this.chapter_obj.isLive == 1 || this.chapter_obj.isLive == 2) {
          this.sources = this.chapter_obj.live;
        } else if (this.chapter_obj.isLive == 0) {
          this.getVideoLastTime();
          this.closeConnection().then(() => {
            this.initWebSocket();
          });
          this.sources = this.chapter_obj.filePath;
        } else if (this.chapter_obj.isLive == 3) {
          this.$nextTick(() => {
            let dom = document.getElementById("tuwen_box");
            console.log("dom", dom);
          });
        }
        //试看
        // if(this.chapter_obj.isJump === 1){
        //   if(this.chapter_obj.isLive == 0){
        //     this.is_had_course = true;
        //     console.log("试看")
        //     this.getVideoLastTime();
        //     this.initWebSocket();
        //   }

        // }else{
        //   this.is_had_course = false;
        // }
      }
    },
    buy_record_list(new_val, old_val) {
      this.set_had_course();
    },
    chapter_obj(new_val, old_val) {
      console.log("章节发生变化 => ", new_val);
      // this.$nextTick(()=>{
      //   let dom = document.getElementById('tuwen_box');
      //   // dom.addEventListener('scroll',()=>{
      //   //   console.log(dom.scrollTop + dom.clientHeight,dom.scrollHeight);
      //   //   if (dom.scrollTop + dom.clientHeight == dom.scrollHeight) {
      //   //     console.log('浏览结束');
      //   //   }
      //   // })
      //   dom.onscroll = function (){
      //     console.log(dom.scrollTop + dom.clientHeight,dom.scrollHeight);
      //     if (dom.scrollTop + dom.clientHeight == dom.scrollHeight) {
      //       console.log('浏览结束');
      //     }
      //   }
      // })
      if (new_val.isCustom) {
        window.location.href = new_val.live;
      }
    }
  },
  activated() {
    this.initPage();
  },
  methods: {
    ...mapActions(["initMember", "initBuyCourseRecord"]),
    ...mapMutations([
      "SET_IS_LOADING",
      "UPDATE_USERINFO",
      "UPDATE_BUYRECORD_LIST",
      "UPDATE_SIGN_IN_COURSE_LIST"
    ]),
    //获取拼团商品信息
    async getGroupBooking() {
      this.SET_IS_LOADING(true);
      let result = await getGroupBookingListByCourse({
        sort: "id desc",
        goodsId: this.courseId
      });
      console.log("拼团信息：", result);
      if (result && result.data && result.data.code == 200) {
        const { rows } = result.data.data;
        if (rows.length > 0) {
          this.gbConfig = { ...rows[0], is_set: true };
        } else {
          this.gbConfig = { ...rows[0], is_set: false };
        }
        this.checkIsPublishBefore();
      } else {
      }
      this.SET_IS_LOADING(false);
    },
    //是否发起过该商品的拼单
    async checkIsPublishBefore() {
      this.SET_IS_LOADING(true);
      const { id } = this.gbConfig;
      let result = await getGroupBookingGroupsByCourseAndUser({
        goodsId: id,
        userId: this.user_info.id
      });
      if (result && result.data && result.data.code == 200) {
        const { data } = result.data;
        if (data && !data.goodsTroopsStatus) {
          this.isPublishedBefore = true;
        } else {
          this.isPublishedBefore = false;
        }
      } else {
        this.isPublishedBefore = false;
      }
      this.SET_IS_LOADING(false);
    },
    //设置我的作业报告的数据
    setTask(obj, status, event) {
      if (status) {
        event.stopPropagation();
        return;
      }
      if (obj && obj.taskType == 2) {
        this.taskObj = obj;
      } else {
        console.log("跳转");
        this.$router.push("/m/task-paper?taskId=" + obj.id);
      }
    },
    afterRead(file) {
      let params = {
        userId: this.user_info.id,
        file: file,
        taskId: this.taskObj.id
      };
      this.uploadFile(params);
      return false;
    },
    async uploadFile(params) {
      this.SET_IS_LOADING(true);
      console.log(params);
      let fd = new FormData();
      Object.keys(params).forEach(i => {
        if (params[i] || params[i] === 0) {
          fd.append(i, params[i]);
        }
      });
      let result = await saveUserTask(fd);
      if (result && result.data && result.data.code == 200) {
        this.$toast("上传作业成功！");
        this.getMyTask();
      } else if (result && result.data && result.data.code == 1001) {
        this.$toast(result.data.msg);
      } else {
        this.$toast("上传作业失败！");
      }
      this.SET_IS_LOADING(false);
      return false;
    },
    async downloadResource(url, taskName) {
      // 如果是小程序内
      /* 在小程序环境下载文件 */
      if (this.is_in_minigram) {
        wx.miniProgram.navigateTo({
          url: `/pages/download/index?downloadUrl=${url}`,
          success: function() {
            console.log("成功跳转小程序");
          },
          fail: function() {
            console.log("跳转小程序失败");
          },
          complete: function() {
            console.log("完成");
          }
        });
        /* 调起微信小程序 */
        return;
      }
      this.SET_IS_LOADING(true);
      let result = await downloadReport(url);
      const content = result.data;
      const blob = new Blob([content]);
      let fileName = taskName + "." + url.replace(/(.*\.)/, ""); // 自定义文件名+后缀;
      if ("download" in document.createElement("a")) {
        console.log("非IE下载");
        // 非IE下载
        const elink = document.createElement("a");
        elink.download = fileName;
        elink.style.display = "none";
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
        URL.revokeObjectURL(elink.href); // 释放URL 对象
        document.body.removeChild(elink);
      } else {
        // IE10+下载
        console.log("IE10+下载");
        navigator.msSaveBlob(content, fileName);
      }
      this.SET_IS_LOADING(false);
    },
    //获取我的作业
    async getMyTask() {
      this.SET_IS_LOADING(true);
      let params = {
        courseId: this.courseId
      };
      let result = await getMyTaskList(params);
      if (result && result.data && result.data.code == 200) {
        this.myTaskList = result.data.data.rows.map(item => {
          return {
            ...item,
            videoHierarchy: item.videoHierarchy
              ? JSON.parse(item.videoHierarchy)
              : []
          };
        });
      } else {
        this.$toast(this.$t("locale.pc.classroom.t43"));
      }
      this.SET_IS_LOADING(false);
    },
    async courseSignInHandle() {
      if (this.maySignInCourse && !this.signInCourseFlag) {
        this.signInCourseFlag = true;
        this.SET_IS_LOADING(true);
        let result = await saveCourseSignIn({
          courseId: this.courseId
          // userId:this.user_info.id
        });
        if (result && result.data && result.data.code == 200) {
          this.$toast("签到成功");
          this.UPDATE_SIGN_IN_COURSE_LIST(result.data.data);
          this.maySignInCourse = false;
          this.signInCourseFlag = false;
        } else {
          this.$toast("服务不可用");
        }
        this.SET_IS_LOADING(false);
      } else {
        return false;
      }
    },
    // 签到倒计时
    countDown() {
      if (this.countDownTimer) {
        clearInterval(this.countDownTimer);
        this.countDownTimer = null;
      }
      let signInCourseIndex = this.sign_in_course_list.findIndex(item => {
        return item.courseId == this.courseId;
      });
      if (signInCourseIndex != -1) {
        this.maySignInCourse = false;
        return;
      }
      let timeSecond = 5 * 60;
      this.countDownTimer = setInterval(() => {
        if (this.hasSignInCourse) {
          clearInterval(this.countDownTimer);
          this.countDownTimer = null;
          return;
        }
        timeSecond--;
        if (timeSecond <= 0) {
          this.maySignInCourse = true;
          clearInterval(this.countDownTimer);
          return;
        }
        let m = Math.floor(timeSecond / 60);
        let s =
          Math.floor(timeSecond % 60) < 10
            ? "0" + Math.floor(timeSecond % 60)
            : Math.floor(timeSecond % 60);
        this.countDownSecond = m + ":" + s;
      }, 1000);
    },
    // 查找可以播放的视频章节列表
    findMinVedioChapter(vedioArr) {
      vedioArr.map(item => {
        if (item.children.length > 0) {
          this.findMinVedioChapter(item.children);
        } else {
          this.minChapterVedioList.push(item);
        }
      });
    },
    async pushRouter(item) {
      if (item.children && item.children.length > 0) {
        return;
      }
      // console.log(item);
      // return
      // 保留阿里云直播,跳转到指定的直播地址
      if ((item.isLive == 1 || item.isLive == 2) && item.videoInfo) {
        // console.log(item); // 直播id
        let result = await getVideoUrl(item.videoInfo.id);
        // console.log(data);
        if (result && result.data && result.data.code == 200) {
          location.href = result.data.data.liveUrl;
        } else if (result && result.data && result.data.code == 1001) {
          this.$Message.error(result.data.msg);
        } else {
          this.$Message.error("数据请求失败");
        }
        // 拦截加载项和阻止函数
        this.SET_IS_LOADING(false);
        return;
      } else if (item.isLive == 2 && item.videoInfo) {
        this.$toast("小班课暂不支持在在手机上观看");
        return;
      }
      if (this.token && Object.keys(this.user_info).length > 0) {
        this.$router.replace({
          path: "",
          query: {
            id: this.courseId,
            chapterId: item.id
          }
        });
      } else {
        this.$dialog
          .confirm({
            title: "提示",
            message: "您尚未登录，请先登录再观看哟！"
          })
          .then(() => {
            this.$router.replace("/m/login");
          })
          .catch(() => {
            return false;
          });
      }
    },
    onClickLeft() {
      this.$router.back();
    },
    setSources(url) {
      this.sources = url;
    },
    async getData() {
      return new Promise(async (res, rej) => {
        this.SET_IS_LOADING(true);
        let result = await getCourse({
          id: this.courseId
        });
        if (result && result.data && result.data.code == 200) {
          const { data } = result.data;
          if (data && data.rows && data.rows.length > 0) {
            this.course_obj = data.rows[0];
            this.getTeacherFun();
          }
        } else {
          this.$toast(
            this.$t("locale.mobile.courseDetail.t18") + result &&
              result.data &&
              result.data.msg
          );
        }
        this.SET_IS_LOADING(false);
        res();
      }).then();
    },
    arrToTree(trimChapterList) {
      let _LEVEL_OBJECT = {};
      //找出最深的层数
      let _MAX_ = trimChapterList.reduce((accumulator, currentValue) => {
        if (accumulator.chapterLevel > currentValue.chapterLevel) {
          return accumulator;
        } else {
          return currentValue;
        }
      }).chapterLevel;
      if (!_MAX_) {
        return trimChapterList;
      }
      for (let i = 1; i < _MAX_ + 1; i++) {
        _LEVEL_OBJECT = {
          ..._LEVEL_OBJECT,
          [i]: trimChapterList
            .map((item, index) => {
              if (item.chapterLevel == i) {
                return item;
              }
            })
            .filter(item => item !== undefined)
        };
      }
      for (let i = _MAX_; i >= 1; i--) {
        if (i < _MAX_) {
          _LEVEL_OBJECT[i] = _LEVEL_OBJECT[i].map((item, index) => {
            return {
              ...item,
              children: _LEVEL_OBJECT[i + 1]
                .map((item2, index2) => {
                  if (item2.fatherLevelId == item.id) {
                    return item2;
                  }
                })
                .filter(item2 => item2 !== undefined)
            };
          });
        }
      }
      return _LEVEL_OBJECT[1];
    },
    async getChapterList() {
      return new Promise(async (res, rej) => {
        this.SET_IS_LOADING(true);
        let result = await getChapter({
          courseId: this.courseId
        });
        if (result && result.data && result.data.code == 200) {
          const { data } = result.data;
          if (data && data.rows && data.rows.length > 0) {
            // this.chapter_list = data.rows;
            //学习进度显示
            await this.getLastStudyList();
            // console.log("-c-c-c---c-c--c--c-c", this.lastStudyDoneList);
            let videoDoneArr = data.rows.map(item => {
              return this.lastStudyDoneList.filter(
                items => items.vedioId == item.id
              ).length > 0
                ? { ...item, isDone: 1 }
                : { ...item };
            });
            // console.log("-c-c-c---c-c--c--c-c", videoDoneArr);
            this.chapter_list = videoDoneArr;

            let trimChapterList = [];
            trimChapterList = this.chapter_list.map(i => {
              return {
                ...i,
                children: []
              };
            });
            // this.chapter_tree = this.arrToTree(trimChapterList);
            this.chapter_tree = this.orderList(
              this.handleTree(trimChapterList, "id", "fatherLevelId")
            );

            this.findMinVedioChapter(this.chapter_tree);

            this.chapter_active = this.chapter_list.map(i => i.id);
            let chapter_arr = this.chapter_list.filter(
              i => i.id == this.chapterId
            );
            if (chapter_arr.length > 0) {
              this.$set(this, "chapter_obj", chapter_arr[0]);
              if (this.chapter_obj.isLive == 1) {
                this.sources = this.chapter_obj.live;
              } else {
                this.sources = this.chapter_obj.filePath;
              }
            } else {
              let Deepest_chapter;
              const getChapterObj = arr => {
                if (
                  !Object.keys(arr[0]).includes("children") ||
                  arr[0].children.length === 0
                ) {
                  // console.log(arr[0]);
                  Deepest_chapter = arr[0];
                  return;
                } else {
                  getChapterObj(arr[0].children);
                }
              };
              getChapterObj(this.chapter_tree);
              this.$set(this, "chapter_obj", Deepest_chapter);
              if (this.is_mobile) {
                this.$router.replace({
                  path: "/m/course-play",
                  query: {
                    id: this.courseId,
                    chapterId: this.chapter_obj.id
                  }
                });
              } else {
                this.$router.replace({
                  path: "/course-detail",
                  query: {
                    id: this.courseId,
                    chapterId: this.chapter_obj.id
                  }
                });
              }
              if (this.chapter_obj.isLive == 1) {
                this.sources = this.chapter_obj.live;
              } else {
                this.sources = this.chapter_obj.filePath;
              }
            }
          }
          this.set_had_course();
        } else {
          this.$toast(
            this.$t("locale.mobile.courseDetail.t19") + result &&
              result.data &&
              result.data.msg
          );
        }
        this.SET_IS_LOADING(false);
        res();
      }).then();
    },
    /**
     * 构造树型结构数据
     * @param {*} data 数据源
     * @param {*} id id字段 默认 'id'
     * @param {*} parentId 父节点字段 默认 'parentId'
     * @param {*} children 孩子节点字段 默认 'children'
     */
    handleTree(data, id, parentId, children) {
      let config = {
        id: id || "id",
        parentId: parentId || "parentId",
        childrenList: children || "children"
      };

      var childrenListMap = {};
      var nodeIds = {};
      var tree = [];
      for (let d of data) {
        let parentId = d[config.parentId];
        if (childrenListMap[parentId] == null) {
          childrenListMap[parentId] = [];
        }
        nodeIds[d[config.id]] = d;
        childrenListMap[parentId].push(d);
      }
      for (let d of data) {
        let parentId = d[config.parentId];
        if (nodeIds[parentId] == null) {
          tree.push(d);
        }
      }
      for (let t of tree) {
        adaptToChildrenList(t);
      }
      function adaptToChildrenList(o) {
        if (childrenListMap[o[config.id]] !== null) {
          o[config.childrenList] = childrenListMap[o[config.id]]
            ? childrenListMap[o[config.id]]
            : [];
        }
        if (o[config.childrenList]) {
          for (let c of o[config.childrenList]) {
            adaptToChildrenList(c);
          }
        }
      }
      return tree;
    },
    // 排序
    orderList(data) {
      data.map(item => {
        if (item.children && item.children.length > 0) {
          return this.orderList(item.children);
        } else {
          return item;
        }
      });
      return data.sort((a, b) => {
        return b.orderNumber - a.orderNumber;
      });
    },
    async getVideoLastTime() {
      let params = {
        userId: this.user_info.id,
        courseId: this.course_obj.id,
        vedioId: this.chapter_obj.id
      };
      let result = await getVideoLastTime(params);
      console.log("上次播放：", result);
      if (result && result.data && result.data.code == 200) {
        const { data } = result.data;
        if (data) {
          if (data.isDone != 1) {
            this.video_obj = { ...data };
          } else {
            this.video_obj = {
              ...data,
              time: 0
            };
          }
        } else {
          this.video_obj = {
            time: 0
          };
        }
      } else {
        this.$toast(
          this.$t("locale.mobile.courseDetail.t19") + result &&
            result.data &&
            result.data.msg
        );
      }
    },
    turnString(num) {
      var re = /^[0-9]+$/;
      var re2 = /^[0-9]+(\.[0-9]{1})$/;
      if (re.test(num)) {
        num += ".00";
      }
      if (re2.test(num)) {
        num += "0";
      }
      return num;
    },
    async toBuy() {
      if (process.client) {
        if (!this.token && Object.keys(this.user_info).length == 0) {
          this.$router.replace("/m/login");
          return;
        }
      }
      if (this.course_obj.isFree) {
        this.toFreeBuy();
        // let __price__ = this.course_obj.isFree
        //   ? 0
        //   : this.course_obj.isDiscount
        //   ? this.course_obj.discountPrice
        //   : this.course_obj.price;
        // this.SET_IS_LOADING(true);
        // let params = {
        //   courseId: this.courseId,
        //   userId: this.user_info.id,
        //   price: this.turnString(__price__)
        // };
        // let result = await saveOrder(params);
        // if (result && result.data && result.data.code == 200) {
        //   const { balance, id, courseId, userId } = result.data.data;
        //   let update_obj = {
        //     balance
        //   };
        //   let course_update_obj = {
        //     id,
        //     courseId,
        //     userId
        //   };
        //   this.UPDATE_USERINFO(update_obj);
        //   this.UPDATE_BUYRECORD_LIST(course_update_obj);
        //   this.SET_IS_LOADING(false);
        //   this.$toast(this.$t("locale.mobile.courseDetail.t23"));
        // } else {
        //   this.SET_IS_LOADING(false);
        //   this.$toast(
        //     this.$t("locale.mobile.courseDetail.t22") +
        //       (result && result.data && result.data.msg)
        //   );
        // }
      } else {
        this.$router.push({
          path: "/m/order",
          query: {
            id: this.course_obj.id
          }
        });
      }
    },
    async toFreeBuy() {
      this.SET_IS_LOADING(true);
      let params = {
        courseId: this.courseId,
        userId: this.user_info.id,
        price: 0.0
      };
      // console.log(params);
      let result = await saveOrder(params);
      if (result && result.data && result.data.code == 200) {
        const { balance, id, courseId, userId, deleted } = result.data.data;
        let update_obj = {
          balance
        };
        let course_update_obj = {
          id,
          courseId,
          userId,
          deleted
        };
        // console.log("更新课程",course_update_obj)
        // console.log("更新课程",result.data.data)
        this.UPDATE_USERINFO(update_obj);
        this.UPDATE_BUYRECORD_LIST(course_update_obj);
        this.SET_IS_LOADING(false);
        this.$toast("报名成功！");
      } else {
        this.SET_IS_LOADING(false);
        this.$toast("报名失败！");
      }
    },
    set_had_course() {
      let res = this.buy_record_list.filter(i => i.courseId == this.courseId);
      if (res.length > 0 && res[0].deleted === 0) {
        this.is_had_course = true;
      } else {
        this.is_had_course = false;
      }
      if (this.is_had_course && this.chapter_obj.isLive == 0) {
        this.getVideoLastTime();
        this.initWebSocket();
      }
      // console.log("当前章节", this.chapter_obj);
      // else if(this.chapter_obj.isJump === 1){
      //   if(this.chapter_obj.isLive == 0){
      //     // this.is_had_course = true;
      //     console.log("试看")
      //     this.getVideoLastTime();
      //     this.initWebSocket();
      //   }

      // }
    },
    async getTeacherFun() {
      this.SET_IS_LOADING(true);
      let params = {
        id: Number(this.course_obj.teacher)
      };
      let result = await getTeacher(params);
      // console.log(result);
      if (result && result.status == 200 && result.data) {
        this.teacher_obj = result.data;
        this.SET_IS_LOADING(false);
      } else {
        this.SET_IS_LOADING(false);
        this.$toast(
          this.$t("locale.mobile.courseDetail.t19") + result &&
            result.data &&
            result.data.msg
        );
      }
    },
    async getLastStudyList() {
      this.SET_IS_LOADING(true);
      let result = await getLastStudyList({
        userId: this.user_info.id,
        courseId: this.courseId
      });
      console.log("该课程所有章节的进度", result.data.data.rows);
      if (result && result.data && result.data.code == 200) {
        let arr = result.data.data.rows;
        this.lastStudyDoneList = arr.filter(item => item.isDone == 1);
        this.SET_IS_LOADING(false);
      } else {
        this.SET_IS_LOADING(false);
        this.$toast(this.$t("locale.pc.mycourse.play.t15"));
      }
    },
    async updateLastStudyTime() {
      console.log("视频播放完毕");
      let params = {
        userId: this.user_info.id,
        courseId: this.course_obj.id,
        vedioId: this.chapter_obj.id
      };
      let result = await getVideoLastTime(params);
      if (result && result.data && result.data.code == 200) {
        const { data } = result.data;
        console.log("视频播放完毕--请求进度", data);
        let videoDoneArr = this.chapter_list.map(item => {
          return item.id === data.vedioId && data.isDone === 1
            ? { ...item, isDone: 1 }
            : { ...item };
        });
        this.chapter_list = videoDoneArr;
        let trimChapterList = [];
        trimChapterList = this.chapter_list.map(i => {
          return {
            ...i,
            children: []
          };
        });
        // this.chapter_tree = this.arrToTree(trimChapterList);
        this.chapter_tree = this.orderList(
          this.handleTree(trimChapterList, "id", "fatherLevelId")
        );
        // 自动切换下一章节
        let nextVedioIndex = this.chapterVedioList.findIndex(item => {
          return item.id == data.vedioId;
        });
        if (
          nextVedioIndex != -1 &&
          this.minChapterVedioList.length != nextVedioIndex + 1
        ) {
          // console.log("下一章节",nextVedioIndex + 1);
          // console.log("下一章节对象",this.minChapterVedioList[nextVedioIndex + 1]);
          let nextChapter = this.minChapterVedioList[nextVedioIndex + 1];
          this.pushRouter(nextChapter);
        }
      } else {
        this.$toast(
          $t("locale.pc.mycourse.play.t15"),
          result && result.data && result.data.msg
        );
      }
    },
    initWebSocket() {
      if (process.client) {
        if ("WebSocket" in window) {
          //初始化weosocket
          const wsuri = socketUrl + "video/" + this.user_info.id;
          this.websock = new WebSocket(wsuri);
          this.websock.onmessage = this.websocketonmessage;
          this.websock.onopen = this.websocketonopen;
          this.websock.onerror = this.websocketonerror;
          this.websock.onclose = this.websocketclose;

          window.addEventListener("beforeunload", this.closeConnection, false);
        } else {
          this.$toast(this.$t("locale.mobile.courseDetail.t20"));
        }
      }
    },
    websocketonopen() {
      //连接建立之后执行send方法发送数据
      console.log("成功建立socket连接");
      clearTimeout(this.timer);
      this.timer = null;
      this.socketFailedCount = 0;
      // this.websocketsend("hello hello!");
    },
    websocketonerror() {
      //连接建立失败重连
      console.log("socket连接失败！");
      this.retryConnectSocket();
    },
    websocketonmessage(e) {
      //数据接收
      console.log("收到socket:", e);
      try {
      } catch (e) {
        console.log(e);
      }
    },
    websocketsend(time) {
      //数据发送
      let current_timestamp = new Date().getTime();
      let duration = document.querySelector("#videoPlayer > video")
        ? document.querySelector("#videoPlayer > video").duration
        : 0;
      let ratio = time / duration;
      if (duration > 10 * 60) {
        if (duration - time <= 30) {
          //完成
          let data = JSON.stringify({
            type: "lastStudy",
            data: {
              userId: this.user_info.id,
              courseId: this.course_obj.id,
              vedioId: this.chapter_obj.id,
              videoDuration: duration,
              time
            }
          });
          this.websock && this.websock.send(data);
        }
      } else {
        if (time / duration >= 0.95) {
          //完成
          let data = JSON.stringify({
            type: "lastStudy",
            data: {
              userId: this.user_info.id,
              courseId: this.course_obj.id,
              vedioId: this.chapter_obj.id,
              videoDuration: duration,
              time
            }
          });
          this.websock && this.websock.send(data);
        }
      }
      //每隔30秒向服务器提交一次视频观看的进度时间
      if (current_timestamp - this.last_require_lime > 30 * 1000) {
        // console.log("currentTime:", time);
        let data = JSON.stringify({
          type: "lastStudy",
          data: {
            userId: this.user_info.id,
            courseId: this.course_obj.id,
            vedioId: this.chapter_obj.id,
            videoDuration: duration,
            time
          }
        });
        this.websock && this.websock.send(data);
        this.last_require_lime = current_timestamp;
      } else {
        return;
      }
    },
    websocketclose(e) {
      //关闭
      console.log("断开连接", e);
      this.retryConnectSocket();
    },
    closeConnection() {
      return new Promise((res, rej) => {
        try {
          window.removeEventListener("beforeunload", this.closeConnection);
          this.websock && this.websock.close();

          if (this.timer) {
            clearTimeout(this.timer);
            this.timer = null;
            this.socketFailedCount = 0;
          }
        } catch (e) {
          console.log("关闭socket错误：", e);
        }
        res();
      }).then();
    },
    initPage() {
      // if (process.client) {
      //   if (!this.token && Object.keys(this.user_info).length == 0) {
      //     this.$router.replace("/m/login");
      //     return;
      //   }
      // }
      this.getData();
      // this.getBuyCourse();
      // this.set_had_course();
      this.getChapterList();
      if (this.token && Object.keys(this.user_info).length > 0) {
        this.initBuyCourseRecord();
        this.getGroupBooking();
        this.initMember();
        this.getMemberConfig();
        this.getMemberList();
        this.countDown();
        this.getMyTask();
      }
    },
    async getMemberConfig() {
      this.SET_IS_LOADING(true);
      let result = await getMemberConfig();
      console.log("result会员", result);
      if (result && result.data && result.data.code == 200) {
        this.member_config = {
          smallMemberName: result.data.data.smallMemberName,
          middleMemberName: result.data.data.middleMemberName,
          highMemberName: result.data.data.highMemberName,
          isOpenMember: result.data.data.isOpenMember
        };
        console.log(this.member_info);
      } else {
      }
      this.SET_IS_LOADING(false);
    },
    async getMemberList() {
      this.SET_IS_LOADING(true);
      let result = await getMemberList();
      console.log("result", result);
      if (result && result.data && result.data.code == 200) {
        this.memberList = result.data.data.rows.map(item => {
          return { ...item, introduction: JSON.parse(item.introduction) };
        });
      } else {
      }
      this.SET_IS_LOADING(false);
    },
    // async getBuyCourse(){
    //   let result = await downloadFile(url);

    // },
    //blob转base64在调用downloadjs下载
    async handleDownload(url) {
      if (process.client) {
        if (window.hasOwnProperty("flutter_inappwebview")) {
          return;
        }
        const { download } = require("~/static/js/download2.js");
        let result = await downloadFile(url);
        // console.log("result:", result);
        if (result && result.status == 200) {
          let mime_type = getMimeType(url);
          download(
            result.data,
            this.chapter_obj &&
              this.chapter_obj.chapterName + "." + mime_type.str,
            mime_type.mime
          );
        }
      }
    },
    initState() {
      this.active = "chapter";
      this.course_obj = {
        name: "",
        isFree: 0
      };
      this.teacher_obj = {}; //课程老师信息
      this.chapter_list = []; //章节列表
      this.chapter_tree = []; //章节树
      this.chapter_active = []; //折叠面板打开
      this.chapter_obj = {
        courseId: 0,
        chapterName: "",
        chapterIndex: 1,
        chapterLevel: 1,
        chapterDescription: "",
        fatherLevelId: 0,
        live: "hahah",
        courseWarePath: null,
        fileName: "",
        filePath: "",
        fileType: null,
        fileSize: null,
        createTime: 1591012869000,
        createUserId: null,
        createUserName: null,
        updateTime: 1591012869000,
        updateUserId: null,
        updateUserName: null,
        liveEndTime: 1591012869000,
        liveStartTime: 1591012869000,
        isLive: 0
      };
      this.video_obj = {
        time: 0
      }; //视频其他数据
      this.websock = null;
      this.component = "ChapterTree";
      this.component1 = "ChapterWareTree";
      this.sources = "";
      this.is_had_course = false;
      this.last_require_lime = new Date().getTime(); //上次上报视频时间的时间戳
      this.member_config = {
        isOpenMember: 0
      };
      this.memberList = [];
      this.timer = null;
      this.socketFailedCount = 0;
    },
    retryConnectSocket() {
      this.debounce(async () => {
        if (this.socketFailedCount < 10) {
          await this.closeConnection();
          this.initWebSocket();
        } else {
          console.info("websocket fail to connection , please retry later!");
          this.timer = null;
        }
      }, 3000);
    },
    debounce(fn, wait) {
      return !(() => {
        if (this.timer !== null) {
          clearTimeout(this.timer);
        }
        this.timer = setTimeout(fn, wait);
      })();
    }
  },
  created() {
    this.initPage();
  },
  destroyed() {
    this.closeConnection();
    this.initState();
  },
  deactivated() {
    this.closeConnection();
    this.initState();
  },
  mounted() {}
};
</script>

<style lang="scss" scoped>
.page-mobile-course_play {
  .tuwen_box {
    // width: 7.2rem;
    // height: 100%;
    position: fixed;
    top: 0.8rem;
    left: 0;
    z-index: 9;
    width: 7.2rem;
    height: 4rem;
    box-sizing: border-box;
    padding: 0.1rem;
    // display: flex;
    // flex-direction: column;
    // align-items: center;
    // justify-content: center;
    background-color: #fff;
    overflow: auto;
  }
  .signin_box {
    position: fixed;
    // left: .1rem;
    // top: 50%;
    // transform: translateY(-50%);
    top: 0rem;
    right: 0.1rem;
    // width: .8rem;
    width: 1.2rem;
    height: 0.8rem;
    // line-height: .8rem;
    // border-radius: 50%;
    // width: 1rem;
    // height: .5rem;
    // line-height: .5rem;
    // border-radius: .1rem;
    // background: var(--theme-color);

    color: var(--theme-color);
    text-align: center;
    z-index: 2001;
    font-size: 0.2304rem;
    &.may_sign {
      // background: var(--theme-color);
      // color: #ffffff;
      // color: var(--theme-color);
      p {
        display: none;
      }
      .signin_text {
        width: 1.14rem;
        height: 0.5rem;
        line-height: 0.5rem;
        margin-top: 0.15rem;
      }
    }
    p {
      margin: 0.05rem 0;
      // transform: scale(.5);
    }
    .signin_text {
      color: #ffffff;
      // width: .768rem;
      width: 1.14rem;
      height: 0.3264rem;
      line-height: 0.3264rem;
      background-color: var(--theme-color);
      border-radius: 0.057rem;
    }
  }
  .task_list {
    width: 6.624rem;
    margin: 0.3rem auto;
    .task_list_title {
      padding-left: 0.2rem;
      font-size: 0.2688rem;
      height: 0.2688rem;
      line-height: 1;
      font-weight: bold;
      position: relative;
      margin-bottom: 0.2rem;
      &::after {
        content: "";
        position: absolute;
        left: 0;
        top: 0;
        height: 0.2688rem;
        width: 0.0576rem;
        display: block;
        background-color: var(--theme-color);
      }
    }
    .task_list_item {
      width: 6.624rem;
      padding-top: 0.4608rem;
      height: 2.016rem;
      box-sizing: border-box;
      border-bottom: 1px solid #ededf1;
      .video_name {
        font-size: 0.2688rem;
        color: #43474c;
        // margin: .4608rem 0 .1rem;

        margin-bottom: 0.1rem;
        text-overflow: ellipsis;
        overflow: hidden;
        white-space: nowrap;
        letter-spacing: 0.0288rem;
        // font-weight: bold;
      }
      .task_name {
        font-size: 0.2688rem;
        color: var(--theme-color);
        margin-bottom: 0.1727rem;
        text-overflow: ellipsis;
        overflow: hidden;
        white-space: nowrap;
        letter-spacing: 0.0288rem;
        // font-weight: bold;
      }
      .task_btn_list {
        display: flex;
        justify-content: flex-end;
        .task_item_btn {
          width: 1.2288rem;
          height: 0.4608rem;
          border-radius: 0.0768rem;
          border: solid 0.0192rem var(--theme-color);
          font-size: 0.2304rem;
          line-height: 0.4608rem;
          text-align: center;
          color: var(--theme-color);
          &:first-child {
            margin-right: 0.2304rem;
          }
          &.bg_pink {
            color: #ff8a8a;
            border: solid 0.0192rem #ff8a8a;
            opacity: 0.55;
          }
        }
      }
    }
  }
}
</style>
<style lang="scss">
@import "assets/css/richtext.scss";
.page-mobile-course_play {
  .van-nav-bar {
    position: fixed;
    top: 0;
    left: 0;
    width: 7.2rem;
    height: 0.8rem;
    line-height: 0.8rem;
    background-color: var(--theme-color);
    z-index: 9;
    .van-nav-bar__arrow {
      font-size: 0.35rem;
    }
    .van-nav-bar__left,
    .van-nav-bar__right {
      padding: 0.16rem;
      > i {
        font-size: 0.35rem;
        color: #fff;
      }
    }
    .van-nav-bar__text {
      font-size: 0.24rem;
    }
    .van-nav-bar__title {
      font-size: 0.28rem;
      color: #fff;
    }
  }
  .van-tabs__content {
    // margin-top: 0.8rem;
    position: relative;
    z-index: 8;
  }
  .van-tabs__wrap {
    position: fixed;
    top: 4.8rem;
    left: 0;
    z-index: 9;
    width: 7.2rem;
    height: 0.8rem;
    background-color: #fff;
    // &::before {
    //   content: "";
    //   display: block;
    //   height: 0.8rem;
    // }
    // &::after {
    //   position: fixed;
    //   box-sizing: border-box;
    //   content: " ";
    //   pointer-events: none;
    //   border-bottom: 0.02rem solid #ebedf0;
    //   top: 5.7rem;
    //   left: 0;
    //   right: auto;
    //   width: 7.2rem;
    //   height: 0.02rem;
    //   z-index: 9;
    // }
    .van-tabs__nav--line {
      padding-bottom: 0;
    }
    .van-tabs__line {
      bottom: 0;
    }
    .van-tabs__nav {
      position: fixed;
      height: 0.8rem;
      width: 7.2rem;
      top: 4.8rem;
      left: 0;
      background-color: #fff;
    }
  }
  .fixed-box {
    height: 0.8rem;
  }
  .video-box {
    position: fixed;
    top: 0.8rem;
    left: 0;
    z-index: 9;
    width: 7.2rem;
    height: 4rem;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background-color: #000;
    overflow: hidden;
    .bottom-bar {
      width: 100%;
      height: 4rem;
      display: flex;
      flex-direction: column;
    }
    .buyless {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      text-align: center;
      color: #fff;
      font-size: 0.24rem;
      padding: 0.6rem;
      line-height: 1.4;
    }
    .course-price {
      width: 7.2rem;
      height: 0.8rem;
      background-color: var(--theme-color);
      color: #fff;
      display: flex;
      align-items: center;
      font-size: 0.28rem;
      padding: 0 0.2rem;
      .macket-price {
        display: flex;
        align-items: flex-end;
        height: 0.36rem;
        > .van-icon {
          margin-right: 0.06rem;
        }
        .price-font {
          margin-right: 0.04rem;
          font-size: 0.36rem;
          line-height: 0.36rem;
          vertical-align: text-bottom;
        }
      }
      .origin-price {
        display: flex;
        align-items: flex-end;
        padding-left: 0.2rem;
        font-size: 0.22rem;
        height: 0.36rem;
        .price-font {
          font-size: 0.22rem;
          text-decoration: line-through;
        }
      }
      .activity {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: flex-end;
        font-size: 0.18rem;
        color: #fff;
        .van-count-down {
          display: inline-flex;
          padding-left: 0.05rem;
          font-size: 0.18rem;
          line-height: 0.26rem;
          .colon {
            display: inline-block;
            margin: 0 0.04rem;
            color: #fff;
          }
          .block {
            display: inline-block;
            padding: 0 0.08rem;
            color: var(--theme-color);
            font-size: 0.18rem;
            text-align: center;
            background-color: #fff;
            border-radius: 0.05rem;
          }
        }
      }
    }
    .live-info {
      font-size: 0.24rem;
      color: #fff;
      .van-count-down {
        color: #fff;
      }
    }
  }
  .chapter {
    .chapter-box {
      padding: 0.2rem;
      .chapter-list {
        .chapter-title-one {
          background: #f0f4f7;
          color: #3d3f42;
          font-size: 0.288rem;
          padding: 0.2rem;
          font-weight: bold;
        }
        .chapter-title-two {
          padding: 0.2rem 0.4rem;
          background: #f0f4f7;
          color: #3d3f42;
          font-size: 0.288rem;
          font-weight: bold;
        }
        .chapter-one {
          padding: 0.2rem 0.4rem;
          font-size: 0.288rem;
          color: #3d3f42;
          display: flex;
          // justify-content: space-between;
          align-items: center;
          position: relative;
          .chapter-left {
            // width: 80%;
            width: 70%;
          }
          .chapter-right {
            width: 20%;
            font-size: 0.2304rem;
            height: 0.46rem;
            border: 0.02rem solid var(--theme-color);
            text-align: center;
            line-height: 0.46rem;
            background: #ffffff;
            color: var(--theme-color);
            border-radius: 0.1rem;
          }
          .tag-study {
            position: absolute;
            right: 0;
            top: 50%;
            transform: translateY(-50%);
          }
        }
        .chapter-two {
          padding: 0.2rem;
          font-size: 0.288rem;
          color: #3d3f42;
          display: flex;
          // justify-content: space-between;
          align-items: center;
          position: relative;
          .chapter-left {
            // width: 80%;
            width: 68%;
          }
          .tag-study {
            position: absolute;
            right: 0;
            top: 50%;
            transform: translateY(-50%);
          }
          .chapter-right {
            width: 20%;
            font-size: 0.2304rem;
            height: 0.46rem;
            border: 0.02rem solid var(--theme-color);
            text-align: center;
            line-height: 0.46rem;
            background: #ffffff;
            color: var(--theme-color);
            border-radius: 0.1rem;
          }
        }
        .chapter-one.active,
        .chapter-two.active {
          .chapter-left {
            color: var(--theme-color);
          }
        }
      }
    }
  }

  .detail,
  .chapter,
  .courseware {
    padding: 0.2rem 0;
    .ware {
      display: flex;
      justify-content: space-between;
      padding: 0.2rem 0.4rem;
      .ware-left {
        width: 80%;
        font-size: 0.288rem;
        color: var(--theme-color);
      }
      .ware-right {
        font-size: 0.2304rem;
        height: 0.46rem;
        width: 0.8448rem;
        border-radius: 0.1rem;
        border: 0.02rem solid var(--theme-color);
        text-align: center;
        line-height: 0.46rem;
        background: #ffffff;
        color: var(--theme-color);
        a {
          color: var(--theme-color);
        }
      }
    }
  }
  .detail {
    .course-name {
      padding: 0 0.2rem;
      color: #010101;
      font-size: 0.26rem;
    }
    .van-cell {
      padding: 0 0.2rem;
      margin-top: 0.2rem;
      &::after {
        display: none;
      }
    }
    .course-teacher {
      display: flex;
      .teacher-icon {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 0.9rem;
        height: 0.9rem;
        > img {
          width: 100%;
          height: auto;
        }
      }
      .teacher-info {
        flex: 1;
        padding-left: 0.1rem;
        .teacher-name {
          font-size: 0.26rem;
          color: #010101;
        }
        .teacher-post {
          margin-top: 0.05rem;
          color: #999;
          font-size: 0.22rem;
        }
      }
    }
    .notice-bar {
      margin-top: 0.2rem;
    }
    .course-desc {
      padding: 0.2rem 0.2rem;
      .desc-tt {
        margin-top: 0.4rem;
        color: #010101;
        font-size: 0.26rem;
      }
      .desc-tx {
        margin-top: 0.2rem;
        font-size: #888;
        font-size: 0.22rem;
      }
    }
  }
  .chapter,
  .courseware {
    padding: 0 0 0 0;
    .van-collapse-item__content {
      padding: 0;
    }
    .van-collapse-item__wrapper {
      padding-left: 0.3rem;
    }
    .van-hairline--top-bottom::after,
    .van-hairline-unset--top-bottom::after {
      border-top: 0;
    }
    .van-hairline--top::after,
    .van-cell:not(:last-child)::after {
      display: none;
    }
    .no-arrow {
      > .van-cell {
        > .van-icon {
          display: none;
        }
      }
    }
  }
  .courseware {
    .download-btn {
      display: block;
      font-size: 0.26rem;
      padding: 0.2rem;
    }
    .preview-iframe {
      width: 7.2rem;
      height: 6.5rem;
    }
    .preview-img {
      width: 100%;
      height: auto;
    }
    .WACPageBorder {
      width: 100% !important;
      height: 100% !important;
      top: 0 !important;
      left: 0 !important;
      border: none !important;
    }
  }
  .bottom-area {
    height: 1rem;
    .btn-buy {
      box-sizing: content-box;
      position: fixed;
      left: 0;
      bottom: 0;
      width: 7.2rem;
      height: 1rem;
      box-shadow: 0 0 0.1rem 0 rgba(0, 0, 0, 0.1);
      display: flex;
      align-items: center;
      background-color: #fff;
      z-index: 99;
      > .van-button {
        margin: 0 0.2rem;
        border-radius: 0.5rem;
      }
    }
    @supports (bottom: constant(safe-area-inset-bottom)) {
      .btn-buy {
        padding-bottom: constant(safe-area-inset-bottom);
      }
    }
    @supports (bottom: env(safe-area-inset-bottom)) {
      .btn-buy {
        padding-bottom: env(safe-area-inset-bottom);
      }
    }
  }
  .xgplayer-skin-default .xgplayer-loading {
    width: 1.2rem;
    height: 1.2rem;
    margin: -0.6rem auto auto -0.6rem;
    > svg {
      width: 100%;
      height: 100%;
    }
  }
  .xgplayer-skin-default .xgplayer-enter .xgplayer-enter-spinner {
    width: 1rem;
    height: 1rem;
  }
}
</style>
